import { InputValueType } from '@app-nextmesh/types';
import { Card, Typography } from 'antd';
import JSONFormatForm from '../JSONFormatForm';
import { IBaseProps } from './types';
import { useEffect, useRef } from 'react';

interface IProps extends IBaseProps {
  readonly: boolean;
  label: string;
  typeObject: object; // { "Hard": {}, "Linear": {...} } 包含多个键值的JSON对象
  form?: { Type: string; Value: object }; // {"Type": "Hard", "Value": {}}
  onInputChange: (value: any) => void; //  比如：{ Surface Behavior: Hard}
}

export default function Group({
  readonly,
  label,
  typeObject,
  form: initForm,
  onInputChange,
}: IProps) {
  const formRef = useRef(null);
  useEffect(() => {
    formRef.current = initForm;
  }, [initForm]);
  if (!initForm) {
    return <></>;
  }
  const handleInputChange = (name: string, value: InputValueType) => {
    if (!formRef.current) {
      formRef.current = {};
    }
    formRef.current[name] = value;
    onInputChange(formRef.current);
  };
  // typeObject 中包含了Type字段，把Type字段去掉
  const newTypeObject = { ...typeObject };
  delete newTypeObject['Type'];
  delete newTypeObject['HandleChange'];
  return (
    <Card styles={{ body: { padding: 5 } }}>
      <Typography.Text
        style={{ fontWeight: 'bold' }}
        strong>
        {label}
      </Typography.Text>
      <JSONFormatForm
        readonly={readonly}
        formData={initForm}
        formFormat={newTypeObject}
        handleInputChange={handleInputChange}
      />
    </Card>
  );
}
